package com.alipay.rebate.shop.controller.admin;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.ResultGenerator;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.JpushHelper;
import com.alipay.rebate.shop.model.AlipayOrder;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.model.WithDraw;
import com.alipay.rebate.shop.pojo.alipay.TransferReq;
import com.alipay.rebate.shop.pojo.common.ResponseResult;
import com.alipay.rebate.shop.service.admin.AdminCustomerUserService;
import com.alipay.rebate.shop.service.admin.AdminWithdrawService;
import com.alipay.rebate.shop.service.admin.AlipayOrderService;
import com.alipay.rebate.shop.utils.AliPayUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by CodeGenerator on 2019/09/12.
*/
@RestController
@RequestMapping("/admin/alipayOrder")
@ResponseBody
public class AlipayOrderController {
    private final Logger logger = LoggerFactory.getLogger(AlipayOrderController.class);
    @Resource
    private AlipayOrderService alipayOrderService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AdminWithdrawService withDrawService;
    @Resource
    private AdminCustomerUserService userService;
    @Autowired
    private JpushHelper jpushHelper;

//    @PostMapping("/transfer")
//    public ResponseResult add(@RequestBody List<AlipayOrder> alipayOrders) throws AlipayApiException {
//        ResponseResult<List<AlipayOrder>> responseResult = new ResponseResult<>();
//        List<AlipayOrder> resOrders = new ArrayList();
//        for (AlipayOrder alipayOrder : alipayOrders){
//            try {
//                String orderNo = (new Date().getTime())+ AliPayUtil.getRandomChar(5);
//                WithDraw withDraw = withDrawService.get(alipayOrder.getWithdrawId());
//                if(withDraw != null){
//                    if(withDraw.getStatus()==1){
//                        alipayOrder.setAmount(String.valueOf(withDraw.getMoney()));
//                        alipayOrder.setPayeeAccount(withDraw.getAccount());
//                        alipayOrder.setPayeeRealName(withDraw.getRealName());
//                        if(alipayOrder.getPayeeAccount()==null||alipayOrder.getPayeeAccount().equals("")){
//                            alipayOrder.setOrderNo(orderNo);
//                            alipayOrder.setResponseCode("5050");
//                            alipayOrder.setResponseMsg("收款方账号不能为空");
//                            alipayOrder.setCreateTime(new Date());
//                        }else if(alipayOrder.getAmount()==null||alipayOrder.getAmount().equals("")){
//                            alipayOrder.setOrderNo(orderNo);
//                            alipayOrder.setResponseCode("5051");
//                            alipayOrder.setResponseMsg("转账金额不能为空");
//                            alipayOrder.setCreateTime(new Date());
//                        }else if (alipayOrder.getPayeeRealName()==null||alipayOrder.getPayeeRealName().equals("")){
//                            alipayOrder.setOrderNo(orderNo);
//                            alipayOrder.setResponseCode("5052");
//                            alipayOrder.setResponseMsg("收款方真实姓名不能为空");
//                            alipayOrder.setCreateTime(new Date());
//                        }else{ //转账操作
//                            alipayOrder.setOrderNo(orderNo);
//                            AlipayFundTransToaccountTransferResponse response = AliPayUtil.alipayTransfer(alipayOrder);
//                            if(response.getCode().equals("10000")){ //修改提现表状态
//                                WithDraw tempWd = new WithDraw();
//                                tempWd.setWithdrawId(withDraw.getWithdrawId());
//                                tempWd.setHandleTime(new Date());
//                                tempWd.setStatus(2);
//                                //更新提现状态
//                                withDrawService.update(tempWd);
//                                // 推送
//                                jpushHelper.withDrawSuccessPush(String.valueOf(withDraw.getUserId()));
//                            }
//                            alipayOrder.setOrderId(response.getOrderId());
//                            alipayOrder.setPayDate(response.getPayDate());
//                            alipayOrder.setResponseCode(response.getCode());
//                            alipayOrder.setResponseMsg(response.getMsg());
//                            alipayOrder.setCreateTime(new Date());
//                        }
//                    }else{
//                        alipayOrder.setOrderNo(orderNo);
//                        alipayOrder.setResponseCode("5054");
//                        alipayOrder.setResponseMsg("不能进行此次提现，提现状态："+withDraw.getStatus());
//                        alipayOrder.setCreateTime(new Date());
//                    }
//                }else{
//                    alipayOrder.setOrderNo(orderNo);
//                    alipayOrder.setResponseCode("5053");
//                    alipayOrder.setResponseMsg("提现表没有相应数据");
//                    alipayOrder.setCreateTime(new Date());
//                }
//                alipayOrderService.save(alipayOrder);
//                resOrders.add(alipayOrder);
//            }catch (Exception e){
//                logger.error("alipay transfer error : {}",e.toString());
//                responseResult.setMsg("服务器异常，部分转账未完成执行");
//                responseResult.setStatus(5000);
//                responseResult.setData(resOrders);
//                return  responseResult;
//            }
//        }
//        responseResult.setData(resOrders);
//        return  responseResult;
//    }

    @PostMapping("/transfer")
    public ResponseResult add(@RequestBody TransferReq transferReq) throws AlipayApiException {
        String key = "transfer";
        String values = stringRedisTemplate.opsForValue().get(key);
        logger.debug("values is : {}",values);
        if (values != null) {
            throw new BusinessException("请求过快", StatusCode.INTERNAL_ERROR);
        }
        stringRedisTemplate.opsForValue().set(key,key,3, TimeUnit.SECONDS);
        ResponseResult<List<AlipayOrder>> responseResult = new ResponseResult<>();
        List<AlipayOrder> resOrders = alipayOrderService.transfer(transferReq);
        responseResult.setData(resOrders);
        return  responseResult;
    }

    @GetMapping("/detail/{id}")
    public ResponseResult<AlipayOrder> detail(@PathVariable("id") Integer id) {
        AlipayOrder activity = alipayOrderService.findById(id);
        return ResultGenerator.genSuccessResponseResult(activity);
    }

    @GetMapping("/list")
    public ResponseResult<PageInfo<AlipayOrder>> list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<AlipayOrder> list = alipayOrderService.getAllTransferOrder();
        PageInfo<AlipayOrder> pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResponseResult(pageInfo);
    }
}
